/**
 * 该文件用于生成新的../help_manual/linkMap.js用
 * 命令： node create_update_linkMapJs.js
 * 或者双击 create_update_linkMapJs.bat文件
 */

require('../help_manual/zh-CN/data/nav_json.js')
let cnNaviData = getFlatData(naviData)

require('../help_manual/en-US/data/nav_json.js')
let enNaviData = getFlatData(naviData)

require('../help_manual/linkMap.js')
let newLinkMap = getLinkMapFromNaviDta(cnNaviData, enNaviData)
writeTolLinkMapJs(newLinkMap)
writeJsVerToHtml()

// --------------------------- 函数定义

function getFlatData(treeData) {
  let data = []
  treeData.forEach(n => {
    data.push(n)
    if (n.children) {
      data = [...data, ...getFlatData(n.children)]
    }
  })
  return data
}

function getLocalId(local) {
  let id = local.replace(/^.*_(\d+)\.html$/, '$1')
  return id
}

function findMapItemByLocalId(localId) {
  for (let i in linkMap) {
    let n = linkMap[i]
    let id = getLocalId(n.cnLink)
    if (id === localId) {
      return n
    }
  }
  return null
}

// 从源json数据中提炼linkMap数据
function getLinkMapFromNaviDta(cnNaviData, enNaviData) {
  let newLinkMap = {}

  cnNaviData.forEach(n => {
    let localId = getLocalId(n.local)
    if (!newLinkMap[localId]) {
      newLinkMap[localId] = {}
    }
    newLinkMap[localId]['vsKey'] = ''
    newLinkMap[localId]['localId'] = localId
    newLinkMap[localId]['cnTitle'] = n.name
    newLinkMap[localId]['cnLink'] = n.local
  })

  enNaviData.forEach(n => {
    let localId = getLocalId(n.local)
    if (!newLinkMap[localId]) {
      newLinkMap[localId] = {}
    }
    newLinkMap[localId]['vsKey'] = ''
    newLinkMap[localId]['localId'] = localId
    newLinkMap[localId]['enTitle'] = n.name
    newLinkMap[localId]['enLink'] = n.local
  })

  return newLinkMap
}

// 将提炼的数据合并写入linkMap.js文件
function writeTolLinkMapJs(newLinkMap) {
  const fs = require('fs')
  const path = require('path')

  let _merge = require('lodash/merge')
  newLinkMap = _merge({}, newLinkMap, linkMap)
  let json = JSON.stringify(newLinkMap, null, 2)
  let code = `linkMap = ${json}`
  let jsFile = path.resolve('../help_manual/linkMap.js')
  fs.writeFileSync(jsFile, code)
}

function writeJsVerToHtml() {
  const fs = require('fs')
  const path = require('path')

  let htmlFile = path.resolve('../help_manual/index_iframe.html')
  let htmlCode = fs.readFileSync(htmlFile).toString()
  let time = new Date().getTime()
  htmlCode = htmlCode.replace(/linkMap\.js[^"]+/, `linkMap.js?t=${time}`)
  fs.writeFileSync(htmlFile, htmlCode)
}
